import DEL_ICON from '@/assets/image/del_sm.png';
import MESSAGE from '@/assets/image/message.png';
import { delConver, getConversationsList } from '@/services/ant-design-pro/chatBot';
import { PlusSquareOutlined } from '@ant-design/icons';
import { Button, List, message, Popconfirm } from 'antd';
import React, { useEffect, useState } from 'react';
import './index.less';
interface ListCon {
  id?: number;
  knowledge_base_id?: number; // 知识库id
  user_id?: number; // 用户id
  name?: string; // 名称
  uuid?: string; // uuid
  created_at?: number; // 时间
  select: boolean;
}

const History: React.FC = (props: any) => {
  const { changeId, changeNew, historyRefresh, changeDelCur, knowledgeId } = props;

  const [lastSelItem, setLastSelItem] = useState<ListCon>();

  const [historyList, setHistoryList] = useState<ListCon[]>([]);
  //一周内
  const [weeksList, setWeeksList] = useState<ListCon[]>([]);
  //一周前
  const [earlierList, setEarlierList] = useState<ListCon[]>([]);
  // 获取会话列表
  const getHistoryList = async () => {
    if (knowledgeId === -1) return;
    const params = {
      knowledge_base_id: knowledgeId,
    };
    const res = await getConversationsList(params);
    let list = res.data?.conversations;
    setHistoryList(list);
    console.log(historyList);
    //为空则不执行
    if (!list) return;
    let now = new Date().getTime();
    //一周内
    let weeks = list.filter((i: any) => {
      // return i.created_at >= now - 40 * 60 * 1000;
      return i.created_at >= now - 7 * 24 * 60 * 60 * 1000;
    });
    setWeeksList(weeks);
    //一周前
    let earlier = list.filter((i: any) => {
      // return i.created_at < now - 40 * 60 * 1000;
      return i.created_at < now - 7 * 24 * 60 * 60 * 1000;
    });
    setEarlierList(earlier);
  };
  //新建对话
  const careteNew = () => {
    changeNew(true);
  };
  //点击当前会话
  const handleCurrent = (event: any, item: ListCon) => {
    event.stopPropagation();
    changeId(item.id);
    changeNew(false);
    item.select = true;
    if (lastSelItem) {
      lastSelItem.select = false;
    }
    setLastSelItem(item);
  };
  //删除会话
  const handleDelete = async (event: any, item: any, listName: any) => {
    event.stopPropagation();
    const res = await delConver(item.id);
    if (res.code === 0) {
      message.success('删除成功');
      //删除成功后 删除list中的数据
      if (listName === 'weeksList') {
        let newList = weeksList.filter((i) => i.id !== item.id);
        setWeeksList(newList);
      } else {
        let newList = earlierList.filter((i) => i.id !== item.id);
        setEarlierList(newList);
      }
      changeDelCur(item.id);
    }
  };

  //页面加载完成时执行
  useEffect(() => {
    getHistoryList(); // 获取会话列表
  }, [knowledgeId]);
  useEffect(() => {
    // 在新建对话时才执行
    if (historyRefresh) {
      getHistoryList(); // 获取会话列表
    }
  }, [historyRefresh]);

  return (
    <div className="listWrap">
      <Button
        block
        style={{ borderColor: '#397BFF', color: '#397BFF', height: '40px' }}
        icon={<PlusSquareOutlined />}
        onClick={careteNew}
      >
        新建对话
      </Button>
      <div className="listBox">
        {weeksList.length > 0 && (
          <List
            header={<div>一周内</div>}
            split={false}
            dataSource={weeksList}
            renderItem={(item) => (
              <List.Item
                key={item.uuid}
                className={'list-item'}
                onClick={(event) => handleCurrent(event, item)}
                actions={[]}
              >
                <div className={'list-item-con' + ' ' + (item.select ? 'hovered' : '')}>
                  <img src={MESSAGE} alt="" height={18} width={18} style={{ marginLeft: '16px' }} />
                  <span className="ellipsis">{item.name}</span>
                  {item.select && (
                    <Popconfirm
                      key={item.uuid}
                      title="确定要删除吗？"
                      onConfirm={(event) => handleDelete(event, item, 'weeksList')}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Button type="link" style={{ color: '#333333' }}>
                        <img src={DEL_ICON} style={{ height: '15px', width: '15px' }} />
                      </Button>
                    </Popconfirm>
                  )}
                </div>
              </List.Item>
            )}
          />
        )}
        {earlierList.length > 0 && (
          <List
            header={<div>更早</div>}
            split={false}
            dataSource={earlierList}
            renderItem={(item) => (
              <List.Item
                key={item.uuid}
                className={'list-item'}
                onClick={(event) => handleCurrent(event, item)}
                actions={[]}
              >
                <div className={'list-item-con' + ' ' + (item.select ? 'hovered' : '')}>
                  <img src={MESSAGE} alt="" height={18} width={18} style={{ marginLeft: '16px' }} />
                  <span className="ellipsis">{item.name}</span>
                  {item.select && (
                    <Popconfirm
                      key={item.uuid}
                      title="确定要删除吗？"
                      onConfirm={(event) => handleDelete(event, item, 'earlierList')}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Button type="link" style={{ color: '#333333' }}>
                        <img src={DEL_ICON} style={{ height: '15px', width: '15px' }} />
                      </Button>
                    </Popconfirm>
                  )}
                </div>
              </List.Item>
            )}
          />
        )}
      </div>
    </div>
  );
};

export default History;
